//
//  RegistrationTypeController.swift
//  EyeVisionForPatients
//
//  Created by qdsg on 2020/4/20.
//  Copyright © 2020 QDSG. All rights reserved.
//

import UIKit

class SERegistrationTypeController: SEBaseViewController {
    
    @IBOutlet weak var searchBar: UISearchBar! {
        didSet {
            searchBar.delegate = self
        }
    }

    var viewModel = SERegistrationDeptViewModel()

    init(with hospitalModel: SEHospitalListItem) {
        self.viewModel.hospitalModel = hospitalModel
        super.init(nibName: nil, bundle: nil)
    }

    required init?(coder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }

    override func viewDidLoad() {
        super.viewDidLoad()
        title = "门诊预约"
        requestDeptData()
    }

    override func setupUI() {
        super.setupUI()
        hospitalNameLabel.text = viewModel.hospitalModel.name
        hospitalGradeLabel.text = " \(viewModel.hospitalModel.level) "

        tableViewLeft.tableFooterView = UIView()
        tableViewLeft.rowHeight = 55
        tableViewLeft.register(UINib(nibName: SERegistrationTypeCell.className, bundle: nil), forCellReuseIdentifier: SERegistrationTypeCell.reuseId)
        tableViewLeft.separatorInset = UIEdgeInsets(top: 0, left: 0, bottom: 0, right: 0)
        tableViewLeft.separatorColor = UIColor.init(hex: "EBECF0")

        tableViewRight.tableFooterView = UIView()
        tableViewRight.rowHeight = 55
        tableViewRight.register(UINib(nibName: SERegistrationTypeListCell.className, bundle: nil), forCellReuseIdentifier: SERegistrationTypeListCell.reuseId)

        viewModel.updateData = { [weak self] status in
            switch status {
            case .success:
                guard let ws = self, ws.viewModel.models.count > 0 else { return }
                ws.tableViewLeft.reloadData()
                ws.tableViewLeft.selectRow(at: ws.viewModel.selectDeptIndexPath,
                                           animated: false,
                                           scrollPosition: .none)
                ws.tableViewRight.reloadData()
            case .auth(let msg):
                self?.presentLoginViewController(selector: #selector(self?.requestDeptData), handle: {
                    SEHUD.showError(message: msg)
                })
            case .failure(let msg):
                SEHUD.showError(message: msg)
            }
        }
    }


    @IBOutlet weak var tableViewLeft: UITableView!
    @IBOutlet weak var tableViewRight: UITableView!
    @IBOutlet weak var headerNoticView: SERegistrationNoticeView! {
        didSet {
            headerNoticView.tapClosure = {
                let agreementView = UINib.loadViewFrom(AgreementAlertView.self)
                agreementView.show(type: .informedLetter)
            }
        }
    }


    @IBOutlet weak var hospitalNameLabel: UILabel!

    @IBOutlet weak var hospitalGradeLabel: UILabel! {
        didSet {
            hospitalGradeLabel.layer.cornerRadius = 3
            hospitalGradeLabel.layer.borderWidth = 1
            hospitalGradeLabel.layer.borderColor = UIColor.init(hex: "FFB32D").cgColor
            hospitalGradeLabel.layer.masksToBounds = true
        }
    }

    @IBAction func hospitalDetailBtnAction(_ sender: Any) {
        let vc = SEHospitalDetailViewController(with: viewModel.hospitalModel.orgId)
        navigationController?.pushViewController(vc, animated: true)
    }


}

// MARK: - UITableViewDataSource, UITableViewDelegate

// tag100:tableViewLeft tag101:tableViewRight
extension SERegistrationTypeController: UITableViewDataSource, UITableViewDelegate {

    // MARK: - UITableViewDataSource

    func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        if tableView.tag == 100 {
            return viewModel.models.count
        }
        if tableView.tag == 101 {
            return viewModel.childDeptModels.count
        }
        return 0
    }
    
    func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        if tableView.tag == 100 {
            let cell = tableView.dequeueReusableCell(withIdentifier: SERegistrationTypeCell.reuseId, for: indexPath) as! SERegistrationTypeCell
            cell.updateData(model: viewModel.deptModel(indexPath: indexPath))
            return cell
        }
        if tableView.tag == 101 {
            let cell = tableView.dequeueReusableCell(withIdentifier: SERegistrationTypeListCell.reuseId, for: indexPath) as! SERegistrationTypeListCell
            cell.updateData(model: viewModel.childDeptModels[indexPath.row])
            return cell
        }
        return UITableViewCell()
    }

    // MARK: - UITableViewDelegate
    
    func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
        if tableView.tag == 100 {
            viewModel.selectDeptIndexPath = indexPath
            tableViewRight.reloadData()
        }
        if tableView.tag == 101 {
            let model = viewModel.childDeptModels[indexPath.row]
            let vc = SERegistrationDateController(with: viewModel.hospitalModel.id, departmentId: model.id)
            vc.title = model.name
            navigationController?.pushViewController(vc, animated: true)
        }
    }
}

extension SERegistrationTypeController {

    @objc func requestDeptData() {
        viewModel.requestDeptData()
    }
}

// MARK: - UISearchBarDelegate

extension SERegistrationTypeController: UISearchBarDelegate {
    func searchBarSearchButtonClicked(_ searchBar: UISearchBar) {
        view.endEditing(true)
        let cancelBtn = searchBar.value(forKey: "cancelButton") as? UIButton
        cancelBtn?.isEnabled = true
    }

    func searchBarCancelButtonClicked(_ searchBar: UISearchBar) {
        view.endEditing(true)
        searchBar.text = ""
        searchBar.setShowsCancelButton(false, animated: true)
        navigationController?.setNavigationBarHidden(false, animated: true)
    }

    func searchBarTextDidBeginEditing(_ searchBar: UISearchBar) {
        searchBar.setShowsCancelButton(true, animated: true)
        navigationController?.setNavigationBarHidden(true, animated: true)
    }

    func searchBarTextDidEndEditing(_ searchBar: UISearchBar) {
        
    }
}
